<?php defined('SYSPATH') or die('No direct script access.');
/**
 *
 * 销售量统计机会任务
 * @author locove 
 *
 */
class Controller_monthsales extends Controller
{
    /**
     * 描述 : 销售量统计
     * 作者 : Edgar.lee
     */
    public function action_index() {
        if( PHP_SAPI !== 'cli' ) return;

        set_time_limit(0);                                                                                              //防超时
        ignore_user_abort(true);

        //判断不为空并且已盘点完
        $add_time = DB::select('add_time')->from('ldt_skus')
            ->limit(1)->execute('newerp')->get('add_time','');
        if($add_time) {
            $h = DB::select(DB::expr("count(id) as num"))->from('ldt_skus')
                ->where('onsale', '=', 1)
                ->where('status', 'IN', array(1,3))
                ->execute('newerp')
                ->get('num', 0);

            if($h)return;
        }

        $temp = strtotime('-1 month', $_SERVER['REQUEST_TIME']);
        $startDate = date('Y-m-01', $temp);                                                                             //上月开始时间
        $endDate = date('Y-m-t 23:59:59', $temp);                                                                       //本月开始时间
        $nowDate = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);                                                       //当前时间
        echo "销售量统计开始 : {$nowDate}\n";

        DB::query(0, 'TRUNCATE `ldt_skus`')->execute('newerp');                                                         //清空原数据

        $sql = "INSERT INTO `ldt_skus` (
            `sku`, `sale`, `add_time`
        ) SELECT
            `sku`, SUM(`quantity`) c, '{$nowDate}'
        FROM
            `deliveryorders`
        WHERE
            `delivery_date` >= '{$startDate}'
        AND `delivery_date` <= '{$endDate}'
        GROUP BY
            `sku`";
        DB::query(Database::INSERT, $sql)->execute('newerp');

        $sql = "SELECT
            `sku`
        FROM
            `ldt_skus`
        GROUP BY
            `sku`";
        while( tool::eachSql($sql, $data) ) {
            foreach($data as &$v) $v = $v['sku'];

            $data = skusystemapi::getSkuAndStatus($data);                                                               //获取订单状态
            foreach($data as &$v) {                                                                                     //获取非正常SKU
                if( $v['status_id'] !== '1' ) {
                    $uSql = "UPDATE 
                        `ldt_skus` 
                    SET 
                        `onsale`='{$v['status_id']}' 
                    WHERE 
                        `sku` = '{$v['sku']}'";
                    DB::query(Database::UPDATE, $uSql)->execute('newerp');                                              //修改SKU状态
                }
            }
        }

        $sql = "SELECT
            COUNT(`id`) c
        FROM
            `ldt_skus`";
        $count = DB::query(Database::SELECT, $sql)->execute('newerp');
        $this->neh();

        $nowDate = time() - $_SERVER['REQUEST_TIME'];
        echo "销售量统计结束 : 导入 {$count[0]['c']} 条, 耗时 {$nowDate} 秒\n";
    }

    /*
     * 提取销量的前98%部分
     */
    public function neh(){
        $skus = DB::select('id', 'sku', 'sale')->from('ldt_skus')
            ->order_by('sale', 'DESC')
            ->execute('newerp')->as_array();

        $sale_all = DB::select(DB::expr('sum(sale) as num'))->from('ldt_skus')
            ->execute('newerp')->get('num',0);

        $sales = 0;
        $stop_ids = array();
        if($sale_all==0)return;
        foreach($skus as $sku) {
            if(!empty($stop_ids)){
                $stop_ids[] = $sku['id'];
            }else{
                $sales += $sku['sale'];
                if(round($sales/$sale_all,3) > 0.98){
                    $stop_ids[] = $sku['id'];
                }
            }
        }

        DB::delete("ldt_skus")->where('id', 'IN', $stop_ids)->execute('newerp');
    }
}
